package com.examples.application;

import com.examples.model.BaseResp;
import com.examples.util.CustomException;
import com.examples.util.MessageUtil;
import com.examples.util.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * process the service exception
     * @param e the service exception
     * @return the response
     */
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseResp globalCustomException(CustomException e) {
        return MessageUtil.failResponse(e.getErrorCode(), e.getErrorMsg(), e.getVariables());
    }

    /**
     * process the database exception
     * @param e the database exception
     * @return the response
     */
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResp globalDataBaseException(DataAccessException e) {
        log.error("process exception caused by the database error", e);
        return MessageUtil.failResponse(ResultCodeEnum.OTHER_INNER_ERROR.getResultCode(), "database error");
    }

    /**
     * process the uncaught exception
     * @param e the uncaught exception
     * @return the response
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public BaseResp globalException(HttpServletRequest req, Exception e) {
        log.error("system inner error, reqUrl=" + req.getPathInfo(), e);
        return MessageUtil.failResponse(ResultCodeEnum.OTHER_INNER_ERROR.getResultCode(), "system inner error");
    }
}
